package com.itheima.exerciseTest.method40_49.method48;

import java.io.*;
import java.text.DecimalFormat;
import java.util.UUID;

public class ThreadCopyFile implements Runnable {
    private File file;
    public ThreadCopyFile(File file){
        this.file = file;
    }
    @Override
    public void run() {
        String fileName = file.getName();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            long total_len = file.length();
            System.out.println("total_len = " + total_len);

            bis = new BufferedInputStream(new FileInputStream(file));

            bos = new BufferedOutputStream(new FileOutputStream("backBurner\\a\\" + UUID.randomUUID().toString() + ".jpg"));

            DecimalFormat df = new DecimalFormat("##%");
            byte[] bytes = new byte[1024];
            int len;
            long length = 0L;
            while ((len = bis.read(bytes)) != -1) {
                length += len;
                String format = df.format(length *1.0 / total_len);
                System.out.println(fileName + "复制了：" + format);
                bos.write(bytes, 0, len);
                bos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(bis != null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
